package com.apple1.commonutil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.apple1.commonutil.common.SmsResponse;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.net.URLEncoder;

/**
 *  发送网络请求
 * @author chencheng
 * @date 2019-01-29
 */
public class SengNetRequest {
    public static final String API_URL = "http://v.juhe.cn/";

    public static final String KEY = "cabfb4e9fc84220e8bd18198d24a59f4";  //Appkey 第三方授予的

    public static final String TPL_ID = "64250"; //短信模板ID

    /**
     * 方法名: 发送短信验证码
     * 处理逻辑:  1.只需要提供手机号和验证码即可
     * note(注意):
     * @param phone
     * @param code
     * @return java.lang.String
     */
    public static SmsResponse send(String phone, String code) throws IOException {
        OkHttpClient client = new OkHttpClient();
        String newCode = URLEncoder.encode("#code#="+code,"UTF-8");
        String url = API_URL + "sms/send?mobile="+phone+"&tpl_id=64250&tpl_value="+newCode+"&dtype=json&key=cabfb4e9fc84220e8bd18198d24a59f4";
        System.out.println(url);
        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()){
                return SmsResponse.error();
            }

            return JSON.parseObject(response.body().string(),new TypeReference<SmsResponse>(){});
        }

    }
    // 测试main
    public static void  main(String[] args) throws IOException {
        System.out.println( SengNetRequest.send("13260960194","818888"));

    }
}
